﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using OznerOA.Common;
using OznerOA.BLL.Workflow.Request;
using System.Threading;
using DevExpress.XtraEditors.ButtonsPanelControl;
using OznerOA.BLL;
using Leestar54.WeChat.WebAPI.Modal;

namespace OznerOA.UI.Workflow.Request
{
    public partial class FrmRequestView : FrmBase
    {
        private RequestViewBLL requestViewBLL = new RequestViewBLL();
        //待办事宜列表
        private List<Model.Workflow> gridValueList = null;
        private WechatBLLAPI wechatBLL = WechatBLLAPI.GetInstance();
        //已处理的流程
        private Dictionary<string, Model.Workflow> FinishedFlow = new Dictionary<string, Model.Workflow>();
        //页面
        private int Page = 1;
        //是否自动提交
        private bool AutoSubmit = false;
        public FrmRequestView()
        {
            InitializeComponent();
            this.Load += FrmRequestView_Load;
        }
        #region 事件
        #region 窗体加载
        private void FrmRequestView_Load(object sender, EventArgs e)
        {
            //读取配置文件的刷新频率
            txtTimes.Text = ConfigModel.WorkflowRequestFrmRequestViewRefreshTimes;
            toogleControlsEnable(true);
            refreshResult(true);
        }
        #endregion
        #region 显示按钮按下
        private void repositoryItemButtonEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if(e.Button.Caption == "显示")
            {
                int rowHandle = gridView1.FocusedRowHandle;
                if (rowHandle >= 0 && rowHandle < gridValueList.Count)
                {
                    Model.Workflow flow = gridValueList[rowHandle];
                    logBLL.Debug(flow.FlowId);

                    BaseResult<string> br = requestViewBLL.GetWorkflowUnoperatorPersons(flow);
                    if(br.Code == Code.OK)
                    {
                        flow.Requestname = br.Object.Replace("\r\n", "");
                        gridControl1.DataSource = null;
                        gridControl1.DataSource = gridValueList;
                    }
                    else
                    {
                        BoxHelper.Error(br.Message);
                    }
                }

            }
        }
        #endregion
        #region 组面板自定义按钮点击事件
        private void groupControl_CustomButtonClick(object sender, DevExpress.XtraBars.Docking2010.BaseButtonEventArgs e)
        {
            switch (e.Button.Properties.Tag.ToString())
            {
                case "START_AUTO_SUBMIT":
                    startAtuoSubmit();
                    break;
                case "STOP_AUTO_SUBMIT":
                    stopAutoSubmit();
                    break;
                case "SHOW_AUTO_SUBMIT":
                    showAutoSubmit();
                    break;
                case "REFRESH":
                    refreshResult(true);
                    break;
                case "PREVIOUS_PAGE":
                    previousPage();
                    break;
                case "NEXT_PAGE":
                    nextPage();
                    break;
            }

        }

        #endregion
        #region 显示行号
        private void gridView1_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.Info.IsRowIndicator && e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }
        #endregion
        #region 设置微信通知复选框改变
        private void chkWechat_CheckedChanged(object sender, EventArgs e)
        {
            if (chkWechat.Checked)
            {
                if (wechatBLL.LoginUser != null)
                {
                    //修改下拉框和按钮的启用状态
                    cboWechatContracts.Enabled = true;
                    btnSendWechat.Enabled = true;
                    //添加联系人信息
                    foreach (Contact contact in wechatBLL.Contracts.Values)
                    {
                        cboWechatContracts.Properties.Items.Add(new ContactComboItem
                        {
                            UserName = contact.UserName,
                            NickName = contact.NickName,
                            RemarkName = contact.RemarkName
                        });
                    }

                }
                else
                {
                    BoxHelper.Info("您尚未登录微信，请先在菜单中选择绑定微信，然后登录!");
                    chkWechat.Checked = false;
                }
            }
            else
            {
                cboWechatContracts.Enabled = false;
                btnSendWechat.Enabled = false;
            }
        }
        #endregion
        #region 微信测试发送按钮
        private void btnSendWechat_Click(object sender, EventArgs e)
        {
            if (wechatBLL.LoginUser != null)
            {
                if (cboWechatContracts.SelectedIndex >= 0)
                {
                    ContactComboItem item = cboWechatContracts.SelectedItem as ContactComboItem;
                    wechatBLL.GetWechatClient().SendMsgAsync("测试发送消息!", item.UserName);
                    logBLL.Debug("已发送测试消息至{0}", item.ToString());
                }
                else
                {
                    BoxHelper.Info("请选择发送联系人!");
                }

            }
            else
            {
                BoxHelper.Info("您尚未登录，请先登录!");
            }
        }
        #endregion
        #endregion
        #region 刷新结果
        private void refreshResult(bool showWait)
        {
            if (showWait)
                ShowWaiting("正在查询已办事宜...");
            BaseResult<List<Model.Workflow>> br = ExecuteBLL<List<Model.Workflow>>(requestViewBLL, "GetAllWorkflowNeedFinished",Page);
            if (br.Code == Code.OK)
            {
                logBLL.Info("查询到第{0}页结果:{1}条",Page , br.Object.Count);
                gridValueList = br.Object;
                ControlDelegateSetProperty(gridControl1, "DataSource", br.Object);
            }
            bsiPage.Caption = Page.ToString();
            if (showWait)
                CloseWaiting();
        }
        #endregion
        #region 上一页
        private void previousPage()
        {
            Page = Page > 1 ? Page - 1 : Page;
            refreshResult(true);
        }
        #endregion
        #region 下一页
        private void nextPage()
        {
            Page++;
            refreshResult(true);
        }
        #endregion
        #region 停止自动提交
        private void stopAutoSubmit()
        {
            AutoSubmit = false;
            toogleControlsEnable(true);
            //隐藏进度条
            beiProgress.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
        }
        #endregion
        #region 开始自动提交
        private void startAtuoSubmit()
        {
            //设置自动提交为true
            AutoSubmit = true;
            //读取刷新频率值
            int refreshTimes = int.Parse(txtTimes.Text);
            //写入配置文件
            ConfigModel.WorkflowRequestFrmRequestViewRefreshTimes = refreshTimes.ToString();
            //禁用所有的交互控件
            toogleControlsEnable(false);

            logBLL.Info("启用待办事宜自动提交,刷新频率:{0}", refreshTimes);
            string action = cboAction.Text;
            ripbProgress.Maximum = refreshTimes;
            ripbProgress.Minimum = -1;
            //微信通知人
            ContactComboItem contact = null;
            //微信通知
            if (chkWechat.Checked)
            {
                if (cboWechatContracts.SelectedIndex >= 0)
                {
                    contact = cboWechatContracts.SelectedItem as ContactComboItem;
                    logBLL.Info("已启用微信通知,接收人:{0}", contact.ToString());
                }else
                {
                    BoxHelper.Info("请选择微信通知接收人!");
                    return;
                }
            }else
            {
                logBLL.Info("未启用微信通知");
            }
            //SynchronizationContext使用此跨线程访问devexpress的控件
            System.Threading.SynchronizationContext sc = System.Threading.SynchronizationContext.Current;
            //显示进度条
            beiProgress.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
            ThreadHelper.StartNewThread(() =>
            {
                //计算过了多少秒
                int count = 0;
                while (AutoSubmit)
                {
                    //计数自增1
                    count++;
                    if (count == refreshTimes+1)
                    {
                        //从第0页开始刷新
                        Page = 1;
                        logBLL.Info("自动刷新结果...");
                        while (true)
                        {
                            refreshResult(false);
                            //判断结果
                            if (gridValueList.Count > 0)
                            {
                                //遍历并自动提交
                                foreach (Model.Workflow flow in gridValueList)
                                {
                                    flow.Action = action;
                                    NewFlowSubmit(flow, contact);
                                }
                            }
                            //说明没有下一页
                            if(gridValueList.Count < 10)
                            {
                                break;
                            }else
                            {
                                Page++;
                            }
                        }
                        count = 0;
                    }
                    //解决跨线程访问控件
                    sc.Post((o) =>
                    {
                        beiProgress.EditValue = count.ToString();
                        beiProgress.Caption = count.ToString();

                        ripbProgress.BeginUpdate();
                    },null);
                    //休眠1秒
                    Thread.Sleep(1000);
                }
                logBLL.Info("已停止待办事宜自动提交");
            }, true);
        }

        #endregion
        #region 新流程的处理
        private void NewFlowSubmit(Model.Workflow flow, ContactComboItem contact)
        {
            //先判断流程是否处理过
            if (FinishedFlow.ContainsKey(flow.Requestid))
            {
                logBLL.Info("流程[{0}]已处理!", flow.FlowId);
            }
            else
            {
                //提交
                logBLL.Info("正在{0}流程:{1}", flow.Action, flow.FlowId);
                //处理结果
                BaseResult<string> br = null;
                if (flow.Action == "提交")
                {
                    br = requestViewBLL.ComplateFlow(flow);
                }
                else if(flow.Action == "退回")
                {
                    br = requestViewBLL.ReturnFlow(flow);
                }else
                {
                    //不处理
                    br = new BaseResult<string>()
                    {
                        Code = Code.OK,
                        Object = "未处理"
                    };
                }
                //设置处理结果
                flow.AutoSubmitResult = br.Code + ":" + br.Object;
                //添加至已处理列表
                FinishedFlow.Add(flow.Requestid, flow);

                logBLL.Info("流程{0}结果:{1}", flow.Action, br.Code + ":" + br.Object);
                if (chkWechat.Checked)
                {
                    if (wechatBLL.LoginUser != null)
                    {
                        if (cboWechatContracts.SelectedIndex >= 0)
                        {
                            //微信通知
                            string tip = string.Format("已处理待办事宜\r\n"
                             + "流程编号:{0}\r\n"
                            + "请求标题:{1}\r\n"
                            + "处理动作:{2}\r\n"
                            + "处理结果:{3}\r\n"
                            + "时间:{4}"
                            , flow.FlowId
                            , flow.RequestName
                            , flow.Action
                            , flow.AutoSubmitResult
                            , DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));
                            wechatBLL.GetWechatClient().SendMsgAsync(tip, contact.UserName);
                            logBLL.Info("已发送微信通知!");
                        }
                        else
                        {
                            logBLL.Info("尚未选择微信通知接收人!");
                        }

                    }
                    else
                    {
                        logBLL.Info("微信尚未登录!");
                    }
                }
            }
            Thread.Sleep(20);//休眠20毫秒继续下一个流程
        }
        #endregion
        #region 切换控件的enable状态
        private void toogleControlsEnable(bool v)
        {
            txtTimes.Enabled = v;
            txtRemarks.Enabled = v;
            cboAction.Enabled = v;
            cboWechatContracts.Enabled = v;
            chkWechat.Enabled = v;
            groupAutoSubmit.CustomHeaderButtons["自动处理"].Properties.Enabled = v;
            groupAutoSubmit.CustomHeaderButtons["停止处理"].Properties.Enabled = !v;
            foreach(GroupBoxButton bb in groupResult.CustomHeaderButtons)
            {
                bb.Enabled = v;
            }
        }
        #endregion
        #region 显示处理结果
        private void showAutoSubmit()
        {
            FrmShowSubmitResult Resul = new FrmShowSubmitResult();
            Resul.RequestViewBLL = requestViewBLL;
            Resul.List = FinishedFlow.Values.ToList();
            Resul.ShowDialog(this);
        }
        #endregion
    }
    #region Commbobox项
    class ContactComboItem
    {
        public string UserName { get; set; }
        public string NickName { get; set; }
        public string RemarkName { get; set; }
        public override string ToString()
        {
            return string.IsNullOrEmpty(RemarkName) ? string.IsNullOrEmpty(NickName) ? UserName : NickName : RemarkName;
        }
    }
    #endregion
}